package com.engine.kq.biz;

import com.alibaba.fastjson.JSONObject;
import com.api.hrm.util.ServiceUtil;
import com.engine.kq.entity.KQBalanceOfLeaveEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.util.KQTransMethod;
import com.weaver.general.TimeUtil;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.StringUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.common.Tools;
import weaver.hrm.resource.ResourceComInfo;
import weaver.systeminfo.SystemEnv;

import java.math.BigDecimal;
import java.util.*;

public class KQLeaveRulesBiz {

    public static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();


    /**
     * 记录日志
     */
    private static KQLog logger = new KQLog();

    /**
     * 根据假期规则ID获取假期规则名称
     *
     * @param ruleId 假期规则的ID
     * @return
     */
    public static String getLeaveName(String ruleId) {
        String leaveName = "";
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        leaveName = kqLeaveRulesComInfo.getLeaveName(ruleId);
        return leaveName;
    }

    /**
     * 判断是否具有假期余额
     *
     * @param ruleId
     * @return
     */
    public static boolean getBalanceEnable(String ruleId) {
        int balanceEnable = 0;
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        balanceEnable = Util.getIntValue(kqLeaveRulesComInfo.getBalanceEnable(ruleId), 0);
        if (balanceEnable == 1) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 判断优先假期类型id字符串
     *
     * @param ruleId
     * @return
     */
    public static String getLeaveids(String ruleId) {
        int schevacationON = 0;
        String schevacation = "-1";

        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        schevacationON = Util.getIntValue(kqLeaveRulesComInfo.getSchevacationON(ruleId), 0);
        if (schevacationON == 1) {
            schevacation=Util.null2s(kqLeaveRulesComInfo.getSchevacation(ruleId), "-1");
        }
        return schevacation;

    }

    /**
     * 判断人员的假期类型id字符串
     *
     * @param scheLeaveids
     * @param resourceId
     * @return
     */
    public static String getusedLeaveids(String scheLeaveids, String resourceId) {
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String subcompanyId = resourceComInfo.getSubCompanyID(resourceId);
            String departmentId = resourceComInfo.getDepartmentID(resourceId);

            List<String> scheLeaveidsList = Util.splitString2List(scheLeaveids, ",");

            /**
             * 加载应用范围为总部的以及应用范围为分部(但是范围中包含了所属分部ID)的假期规则
             */
            RecordSet recordSet = new RecordSet();
            String sql = "select * from kq_LeaveRules ";
            String sqlWhere = " where (isDelete is null or isDelete <>1) and isEnable=1 and balanceEnable=1 ";
            /*如果找不到人员所在分部，则只返回应用范围为总部的假期规则*/
            if (!resourceId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere += " and ( (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere += " and ( (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') ";
                } else {
                    sqlWhere += " and ( (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') ";
                }
            }
            if (!departmentId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere += " or  (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere += " or  (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') ";
                } else {
                    sqlWhere += " or  (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') ";
                }
            }
            if (!subcompanyId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere += " or  (scopeType=1 and ','+scopeValue+',' like '%," + subcompanyId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere += " or  (scopeType=1 and concat(',',scopeValue,',') like '%," + subcompanyId + ",%') ";
                } else {
                    sqlWhere += " or  (scopeType=1 and ','||scopeValue||',' like '%," + subcompanyId + ",%') ";
                }
            }

            sqlWhere += " or scopeType=0 )";
            sql = sql + sqlWhere + " order by showOrder,id ";
            scheLeaveids = "";
            List<String> remleaveidsList = new ArrayList<>();
            recordSet.executeQuery(sql);
            /*如果指定人员所在分部下面单独设置过假期规则，则取分部下面的假期规则*/
            while (recordSet.next()) {
                String leaveid = recordSet.getString("id");//假期类型id
                remleaveidsList.add(leaveid);
            }

            for (String id : scheLeaveidsList) {
                if (remleaveidsList.contains(id)) {
                    if (scheLeaveids.equals("")) {
                        scheLeaveids = id;
                    } else {
                        scheLeaveids += "," + id;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return scheLeaveids;

    }
    /**
     * 获取最小请假单位
     * 1-按天请假
     * 2-按半天请假
     * 3-按小时请假
     * 4-按整天请假
     * 其他：无效数据
     *
     * @param ruleId 指定的假期规则ID
     * @return
     */
    public static int getMinimumUnit(String ruleId) {
        int minimumUnit = -1;//最小请假单位
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1);
        return minimumUnit;
    }

    /**
     * 获取请假时长计算方式
     * 1-按照工作日计算请假时长
     * 2-按照自然日计算请假时长
     * 其他：无效数据
     *
     * @param ruleId 指定的假期规则ID
     * @return
     */
    public static int getComputingMode(String ruleId) {
        int computingMode = -1;//计算请假时长方式
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1);
        return computingMode;
    }

    /**
     * 按照自然日计算请假时长排除节假日、休息日
     * 0-不排除
     * 1-排除节假日
     * 2-排除休息日
     * 1,2-排除节假日和休息日
     *
     * @param ruleId 指定的假期规则ID
     * @return
     */
    public static String getFilterHolidays(String ruleId) {
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        String  filterHolidays = Util.null2s(kqLeaveRulesComInfo.getFilterHolidays(ruleId), "0");
        return filterHolidays;
    }

    /**
     * 获取日折算时长（多少小时算一天）
     *
     * @param ruleId 指定的假期规则ID
     * @return
     */
    public static String getHoursToDay(String ruleId) {
        double hoursToDay = -1;//日折算时长
        int computingMode = -1;//计算请假时长方式
        int minimumUnit = -1;//最小请假单位
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        hoursToDay = Util.getDoubleValue(kqLeaveRulesComInfo.getHoursToDay(ruleId), -1);
        computingMode = Util.getIntValue(kqLeaveRulesComInfo.getComputingMode(ruleId), -1);
        minimumUnit = Util.getIntValue(kqLeaveRulesComInfo.getMinimumUnit(ruleId), -1);
        if (computingMode != 2) {
            hoursToDay = -1;
        }
        return String.format("%.2f", hoursToDay);
    }

    /**
     * 1-按天请假
     * 2-按半天请假
     * 3-按小时请假
     * 4-按整天请假
     *
     * @param minimumUnit
     * @param lan
     * @return
     */
    public static String getMinimumUnitName(String minimumUnit, int lan) {
        String minimumUnitName = "";
        switch (minimumUnit) {
            case "1":
                minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
                break;
            case "2":
                minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
                break;
            case "3":
            case "5":
            case "6":
                minimumUnitName = SystemEnv.getHtmlLabelName(391, lan);
                break;
            case "4":
                minimumUnitName = SystemEnv.getHtmlLabelName(1925, lan);
                break;
            default:
                break;
        }
        return minimumUnitName;
    }

    /**
     * 获取所有的假期规则
     * unitType：1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假、-1：数据异常，无效数据
     *
     * @return
     */
    public static List<Map<String, Object>> getAllLeaveRules() {
        Map<String, Object> ruleMap = new HashMap<String, Object>();
        List<Map<String, Object>> ruleList = new ArrayList<Map<String, Object>>();

        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        kqLeaveRulesComInfo.setTofirstRow();
        while (kqLeaveRulesComInfo.next()) {
            if (kqLeaveRulesComInfo.getIsEnable().equals("1")) {
                ruleMap = new HashMap<String, Object>();
                ruleMap.put("id", kqLeaveRulesComInfo.getId());
                ruleMap.put("name", kqLeaveRulesComInfo.getLeaveName());
                ruleMap.put("unitType", kqLeaveRulesComInfo.getMinimumUnit());
                ruleMap.put("proportion", kqLeaveRulesComInfo.getProportion());
                ruleMap.put("scopeType",kqLeaveRulesComInfo.getScopeType());
                ruleMap.put("scopeValue",kqLeaveRulesComInfo.getScopeValue());
                ruleList.add(ruleMap);
            }
        }
        return ruleList;
    }

    /**
     * 根据人员ID获取其可见的所有假期类型
     *
     * @param resourceId 指定人员ID
     * @return
     */
    public static String getAllLeaveRulesByUserId(String resourceId, String languageId) {
        String resultStr = "";
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String subcomId = resourceComInfo.getSubCompanyID(resourceId);
            String deptId = resourceComInfo.getDepartmentID(resourceId);

            List<String> tempList = new ArrayList<String>();

            Map<String, Object> itemMap = new HashMap<String, Object>();
            List<Object> itemList = new ArrayList<Object>();

            String sql = "select * from kq_leaveRules where 1=1 and (isDelete is null or isDelete <>1) and isEnable=1";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql);
            while (recordSet.next()) {
                String scopeType = recordSet.getString("scopeType");
                String scopeValue = recordSet.getString("scopeValue");
                String leaveName = recordSet.getString("leaveName");
                String id = recordSet.getString("id");

                if (scopeType.equals("1")) {
                    tempList = Util.TokenizerString(scopeValue, ",");
                    if (!tempList.contains(subcomId)) {
                        continue;
                    }
                }

                itemMap = new HashMap<String, Object>();
                itemMap.put("name", Util.formatMultiLang(leaveName, languageId));
                itemMap.put("id", id);
                itemList.add(itemMap);
            }
            resultStr = JSONObject.toJSONString(itemList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultStr;
    }
    public static boolean filterSubLeaveRule(KQLeaveRulesComInfo kqLeaveRulesComInfo, User user, String leaveId) {
        return filterSubLeaveRule(Util.null2String(user.getUID()), kqLeaveRulesComInfo.getScopeType(leaveId), kqLeaveRulesComInfo.getScopeValue(leaveId), Util.null2String(user.getUserSubCompany1()),Util.null2String(user.getUserDepartment()));
    }
    public static boolean filterSubLeaveRule(String userId, String scopeType, String scopeValue, String subCompany, String deptId) {
        boolean isAdmin = ServiceUtil.isAdmin(userId);
        if (isAdmin) {
            return false;
        }
        if ("1".equals(scopeType)) {
            if (scopeValue.indexOf(",") > 0) {
                String[] split = scopeValue.split(",");
                for (String v : split) {
                    if (!StringUtil.isEmpty(v) && v.equals(subCompany)) {
                        return false;
                    }
                }
                return true;
            } else {
                return !scopeValue.equals(subCompany);
            }
        }else if("2".equals(scopeType)){
            if (scopeValue.indexOf(",") > 0) {
                String[] split = scopeValue.split(",");
                for (String v : split) {
                    if (!StringUtil.isEmpty(v) && v.equals(deptId)) {
                        return false;
                    }
                }
                return true;
            } else {
                return !scopeValue.equals(deptId);
            }
        }else if("3".equals(scopeType)){
            if (scopeValue.indexOf(",") > 0) {
                String[] split = scopeValue.split(",");
                for (String v : split) {
                    if (!StringUtil.isEmpty(v) && v.equals(userId)) {
                        return false;
                    }
                }
                return true;
            } else {
                return !scopeValue.equals(userId);
            }
        } else if (StringUtils.isNotEmpty(scopeType) && new BigDecimal(scopeType).compareTo(new BigDecimal("3")) > 0) {
            RecordSet rs1 = new RecordSet();
            rs1.execute("SELECT id FROM cus_fielddata WHERE scope = 'HrmCustomFieldByInfoType' and scopeid = 3 AND " +
                    "field17 in (SELECT CAST(htzt AS VARCHAR(MAX)) FROM uf_jqhtztglb WHERE id = " + scopeType + ")");
            while (rs1.next()) {
                String idT = rs1.getString("id");
                if (StringUtils.isNotEmpty(idT) && StringUtils.equals(idT, userId)) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    /**
     * 初始化年假
     *
     * @param ruleId
     * @return
     */
    public static boolean initAnnualLeave(int ruleId) {
        boolean isInitSuccess = false;
        try {
            /*判断年假是否初始化过*/
            RecordSet recordSet = new RecordSet();
            String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
            recordSet.executeQuery(sql);
            boolean initialized = recordSet.getCounts() > 0;

            /*没有初始化过就新建，已经初始化过就更新*/
            if (initialized) {
                String updateSql = "update kq_LeaveRules set leaveName='年假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," +
                        "isDelete=0,isEnable=1,leaveCode='annualLeave' where id=" + ruleId;
                isInitSuccess = recordSet.executeUpdate(updateSql);
                if (!isInitSuccess) {
                    return false;
                }

                String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
                recordSet.executeUpdate(deleteDetailSql);

                String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
                        "values('年假-总部规则'," + ruleId + ",0,'',3,0,1,0,'','',0,0,0,0)";
                isInitSuccess = recordSet.executeUpdate(insertDetailSql);
                if (!isInitSuccess) {
                    return false;
                }
            } else {
                KQTransMethod kqTransMethod = new KQTransMethod();
                int nextId = kqTransMethod.getNextId();

                String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                        "values(" + nextId + ",'年假-初始化',0,'',1,8,1,1,0,1,'annualLeave')";
                isInitSuccess = recordSet.executeUpdate(insertSql);
                if (!isInitSuccess) {
                    return false;
                }

                String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
                        "values('年假-总部规则'," + nextId + ",0,'',3,0,1,0,'','',0,0,0,0)";
                isInitSuccess = recordSet.executeUpdate(insertDetailSql);
                if (!isInitSuccess) {
                    return false;
                }

                String historySql = "update kq_initHistory set annualLeave=" + nextId + " where id=1";
                isInitSuccess = recordSet.executeUpdate(historySql);

                ruleId = nextId;
            }

            String detailId = "";
            sql = "select * from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
            recordSet.executeQuery(sql);
            if (recordSet.next()) {
                detailId = recordSet.getString("id");
            }
            if (detailId.equals("")) {
                return false;
            }

            /*先删除原来的明细记录，在插入新的明细记录*/
            String detailSql = "delete from kq_WorkingAgeToLeave where leaveRulesId=" + detailId;
            isInitSuccess = recordSet.executeUpdate(detailSql);
            if (!isInitSuccess) {
                sql = "delete from kq_LeaveRules where leaveRulesId=" + detailId;
                recordSet.executeUpdate(sql);
                return false;
            }

            /*插入明细记录*/
            detailSql = "insert into kq_WorkingAgeToLeave(leaveRulesId,lowerLimit,upperLimit,amount) values(?,?,?,?)";
            isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 0, 1, 0);
            isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 1, 10, 5);
            isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 10, 20, 10);
            isInitSuccess = recordSet.executeUpdate(detailSql, detailId, 20, 9999, 15);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return isInitSuccess;
    }

    /**
     * 初始化带薪事假
     *
     * @param ruleId
     * @return
     */
    public static boolean initPaidCompassionateLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='带薪事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='paidCompassionateLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'带薪事假-初始化',0,'',1,8,1,0,0,1,'paidCompassionateLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set paidCompassionateLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化带薪病假
     *
     * @param ruleId
     * @return
     */
    public static boolean initPaidSickLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='带薪病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='paidSickLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'带薪病假-初始化',0,'',1,8,1,0,0,1,'paidSickLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set paidSickLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化调休
     *
     * @param ruleId
     * @return
     */
    public static boolean initVacationLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='调休-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=1," +
                    "isDelete=0,isEnable=1,leaveCode='vacationLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }

            String deleteDetailSql = "delete from kq_LeaveRulesDetail where scopeType=0 and ruleId=" + ruleId;
            rs.executeUpdate(deleteDetailSql);

            String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
                    "values('调休-总部规则'," + ruleId + ",0,'',5,0,1,0,'','',0,0,0,0)";
            isInitSuccess = rs.executeUpdate(insertDetailSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            /*判断系统中是否已经存在调休了，如果已存在，则不允许新建新的调休假期*/
            sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id in (select ruleId from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5)";
            rs.executeQuery(sql);
            if (rs.getCounts() > 0) {
                return false;
            }

            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'调休-初始化',0,'',1,8,1,1,0,1,'vacationLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String insertDetailSql = "insert into kq_LeaveRulesDetail(ruleName,ruleId,scopeType,scopeValue,distributionMode,annualAmount,priority,validityRule,expirationMonth,expirationDay,extensionEnable,extendedDays,releaseRule,calcMethod)" +
                    "values('调休-总部规则'," + nextId + ",0,'',5,0,1,0,'','',0,0,0,0)";
            isInitSuccess = rs.executeUpdate(insertDetailSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set vacationLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化事假
     *
     * @param ruleId
     * @return
     */
    public static boolean initCompassionateLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='事假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='compassionateLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'事假-初始化',0,'',1,8,1,0,0,1,'compassionateLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set compassionateLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化病假
     *
     * @param ruleId
     * @return
     */
    public static boolean initSickLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='病假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='sickLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'病假-初始化',0,'',1,8,1,0,0,1,'sickLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set sickLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化产假
     *
     * @param ruleId
     * @return
     */
    public static boolean initMaternityLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='maternityLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'产假-初始化',0,'',1,8,2,0,0,1,'maternityLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set maternityLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化陪产假
     *
     * @param ruleId
     * @return
     */
    public static boolean initPaternityLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (recordSet.next()) {
            String updateSql = "update kq_LeaveRules set leaveName='陪产假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='paternityLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'陪产假-初始化',0,'',1,8,2,0,0,1,'paternityLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set paternityLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化婚假
     *
     * @param ruleId
     * @return
     */
    public static boolean initMarriageLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='婚假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=2,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='marriageLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'婚假-初始化',0,'',1,8,2,0,0,1,'marriageLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set marriageLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化丧假
     *
     * @param ruleId
     * @return
     */
    public static boolean initFuneralLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='丧假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='funeralLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'丧假-初始化',0,'',1,8,1,0,0,1,'funeralLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set funeralLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 初始化哺乳假
     *
     * @param ruleId
     * @return
     */
    public static boolean initBreastfeedingLeave(int ruleId) {
        /*判断是否初始化过*/
        RecordSet recordSet = new RecordSet();
        RecordSet rs = new RecordSet();
        String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete<>1) and id=" + ruleId;
        recordSet.executeQuery(sql);
        boolean initialized = recordSet.getCounts() > 0;

        /*没有初始化过就新建，已经初始化过就更新*/
        boolean isInitSuccess = false;
        if (initialized) {
            String updateSql = "update kq_LeaveRules set leaveName='哺乳假-初始化',scopeType=0,scopeValue='',minimumUnit=1,hoursToDay=8,computingMode=1,balanceEnable=0," +
                    "isDelete=0,isEnable=1,leaveCode='breastfeedingLeave' where id=" + ruleId;
            isInitSuccess = rs.executeUpdate(updateSql);
            if (!isInitSuccess) {
                return false;
            }
        } else {
            KQTransMethod kqTransMethod = new KQTransMethod();
            int nextId = kqTransMethod.getNextId();

            String insertSql = "insert into kq_LeaveRules(id,leaveName,scopeType,scopeValue,minimumUnit,hoursToDay,computingMode,balanceEnable,isDelete,isEnable,leaveCode)" +
                    "values(" + nextId + ",'哺乳假-初始化',0,'',1,8,1,0,0,1,'breastfeedingLeave')";
            isInitSuccess = rs.executeUpdate(insertSql);
            if (!isInitSuccess) {
                return false;
            }

            String historySql = "update kq_initHistory set breastfeedingLeave=" + nextId + " where id=1";
            isInitSuccess = rs.executeUpdate(historySql);
        }
        return isInitSuccess;
    }

    /**
     * 根据人员ID以及名称获取对应的假期规则ID(主要对于对接小E)
     *
     * @param resourceId 人员ID
     * @param leaveName  假期规则名称
     * @return
     */
    public static List<Object> getLeaveRuleIdByName(String resourceId, String leaveName) {
        List<Object> dataList = new ArrayList<Object>();
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String subcomId = resourceComInfo.getSubCompanyID(resourceId);

            Map<String, Object> dataMap = new HashMap<String, Object>();

            String sql = "select * from kq_LeaveRules where (isDelete is null or isDelete <>1) and isEnable=1 and leaveName like '%" + leaveName + "%'";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql);
            while (recordSet.next()) {
                int scopeType = Util.getIntValue(recordSet.getString("scopeType"), 0);
                String scopeValue = Util.null2String(recordSet.getString("scopeValue"));

                if (scopeType == 1) {
                    List<String> tempList = Util.TokenizerString(scopeValue, ",");
                    if (!tempList.contains(subcomId)) {
                        continue;
                    }
                }

                dataMap = new HashMap<String, Object>();
                dataMap.put("ruleId", recordSet.getString("id"));
                dataMap.put("name", Util.formatMultiLang(recordSet.getString("leaveName"), "7"));
                dataList.add(dataMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataList;
    }

    /**
     * 判断此请假类型是否是由 法定年假+福利年假 组合而成的混合模式
     *
     * @param ruleId 指定的请假类型的id(对应于kq_LeaveRules表的主键ID)
     * @return true--是混合模式、false--不是
     */
    public static boolean isMixMode(String ruleId) {
        boolean flag = false;
        try {
            String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=6 and ruleId=?";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql, ruleId);
            if (recordSet.next()) {
                flag = true;
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return flag;
    }

    /**
     * 获取请假类型的颜色(随机生成)
     *
     * @return
     */
    public static String getColor() {
        String color = "";
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < 6; i++) {
                //随机生成0-15的数值并转换成16进制
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            color = "#" + result.toString().toUpperCase();
        } catch (Exception e) {
            System.out.println("获取16进制字符串异常，返回默认...");
            color = "#00CCCC";
        }
        return color;
    }

    public static String getChildName(String balanceofleaveid){
        String name = "";
        try {
            String sql = "select childId from kq_balanceOfLeave where id=?";
            RecordSet recordSet = new RecordSet();
            KQChildrenComInfo kqChildrenComInfo = new KQChildrenComInfo();
            recordSet.executeQuery(sql, balanceofleaveid);
            if (recordSet.next()) {
                String chlid = Util.null2s(recordSet.getString("childId"), "");
                if(StringUtils.isNotBlank(chlid)){
                    name= kqChildrenComInfo.getChildrenName(chlid);
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return name;
    }
    /**
     * 是否是调休
     * @param ruleId
     * @return
     */
    public static boolean isTiaoXiu(String ruleId){
        boolean flag = false;
        try {
            String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5 and ruleId=?";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql, ruleId);
            if (recordSet.next()) {
                flag = true;
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return flag;
    }

    public static boolean isTiaoXiu(String ruleId, String subCompanyId, String departmentId, String resourceId) {
        boolean flag = false;
        RecordSet recordSet = new RecordSet();
        try {
            KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();
            recordSet.writeLog("isTiaoXiu>>1=" +ruleId+";2="+ subCompanyId+";3="+  departmentId+";4="+ resourceId );
            int distributionMode = Util.getIntValue(detailComInfo.getDistributionMode(ruleId, subCompanyId, departmentId, resourceId), 1);
            if (distributionMode == 5) {
                flag = true;
            }
            recordSet.writeLog("isTiaoXiu>>distributionMode=" +distributionMode);
//            if (!flag) {
            if (true) {

                String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) " +
                        "and distributionMode=5 and ruleId=? ";
                String sqlWhere = "";
                if (!resourceId.equals("")) {
                    if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                        sqlWhere = " and (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') ";
                    } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                        sqlWhere = " and (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') ";
                    } else {
                        sqlWhere = " and (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') ";
                    }
                    recordSet.writeLog("isTiaoXiu>>sql1=" + sql + sqlWhere);
                    recordSet.executeQuery(sql + sqlWhere, ruleId);
                    if (recordSet.next()) {
                        return true;
                    }
                } else if (!departmentId.equals("")) {
                    if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                        sqlWhere = " and (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') ";
                    } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                        sqlWhere = " and (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') ";
                    } else {
                        sqlWhere = " and (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') ";
                    }
                    recordSet.writeLog("isTiaoXiu>>sql2=" + sql + sqlWhere);
                    recordSet.executeQuery(sql + sqlWhere, ruleId);
                    if (recordSet.next()) {
                        return true;
                    }
                } else if (!subCompanyId.equals("")) {
                    if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                        sqlWhere = " and (scopeType=1 and ','+scopeValue+',' like '%," + subCompanyId + ",%') ";
                    } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                        sqlWhere = " and (scopeType=1 and concat(',',scopeValue,',') like '%," + subCompanyId + ",%') ";
                    } else {
                        sqlWhere = " and (scopeType=1 and ','||scopeValue||',' like '%," + subCompanyId + ",%') ";
                    }
                    recordSet.writeLog("isTiaoXiu>>sql3=" + sql + sqlWhere);
                    recordSet.executeQuery(sql + sqlWhere, ruleId);
                    if (recordSet.next()) {
                        return true;
                    }
                } else {
                    sqlWhere = " and scopeType=0 ";
                    recordSet.writeLog("isTiaoXiu>>sql4=" + sql + sqlWhere);
                    recordSet.executeQuery(sql + sqlWhere, ruleId);
                    if (recordSet.next()) {
                        return true;
                    }
                }
            }

            recordSet.writeLog("isTiaoXiu>>flag=" + flag);
        } catch (Exception e) {
            recordSet.writeLog(e.getMessage());
            recordSet.writeLog(e);
        }
        return flag;
    }

    public static int getTiaoXiu(String subCompanyId, String departmentId, String resourceId) {
        int ruleid = 0;
        RecordSet recordSet = new RecordSet();
        try {

            String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) " +
                    "and distributionMode=5 ";
            String sqlWhere = "";
            if (!resourceId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere = " and (scopeType=3 and ','+scopeValue+',' like '%," + resourceId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere = " and (scopeType=3 and concat(',',scopeValue,',') like '%," + resourceId + ",%') ";
                } else {
                    sqlWhere = " and (scopeType=3 and ','||scopeValue||',' like '%," + resourceId + ",%') ";
                }

                recordSet.executeQuery(sql + sqlWhere);
                while (recordSet.next()) {
                    ruleid = recordSet.getInt("ruleId");
                    return ruleid;
                }
            }
            if (!departmentId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere = " and (scopeType=2 and ','+scopeValue+',' like '%," + departmentId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere = " and (scopeType=2 and concat(',',scopeValue,',') like '%," + departmentId + ",%') ";
                } else {
                    sqlWhere = " and (scopeType=2 and ','||scopeValue||',' like '%," + departmentId + ",%') ";
                }

                recordSet.executeQuery(sql + sqlWhere);
                while (recordSet.next()) {
                    ruleid = recordSet.getInt("ruleId");
                    return ruleid;
                }
            }
            if (!subCompanyId.equals("")) {
                if (recordSet.getDBType().equalsIgnoreCase("sqlserver")) {
                    sqlWhere = " and (scopeType=1 and ','+scopeValue+',' like '%," + subCompanyId + ",%') ";
                } else if (recordSet.getDBType().equalsIgnoreCase("mysql")) {
                    sqlWhere = " and (scopeType=1 and concat(',',scopeValue,',') like '%," + subCompanyId + ",%') ";
                } else {
                    sqlWhere = " and (scopeType=1 and ','||scopeValue||',' like '%," + subCompanyId + ",%') ";
                }

                recordSet.executeQuery(sql + sqlWhere);
                while (recordSet.next()) {
                    ruleid = recordSet.getInt("ruleId");
                    return ruleid;
                }
            }

            sqlWhere = " and scopeType=0 ";

            recordSet.executeQuery(sql + sqlWhere);
            while (recordSet.next()) {
                ruleid = recordSet.getInt("ruleId");
                return ruleid;
            }

        } catch (Exception e) {
            recordSet.writeLog(e.getMessage());
            recordSet.writeLog(e);
        }
        return ruleid;
    }

    public static Map<String, String> isRepeat(String ruleid,int scopeType,String scopeValue,User user,String ruleDetailId){
        Map<String, String> result = new HashMap<>();
        result.put("flag","0");//0=未重复，1=重复了不让保存
//        String sql = "select id,ruleid,scopetype,scopevalue,distributionmode from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=5 ";
        String sql = "select id,ruleid,scopetype,scopevalue,distributionmode from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) ";
        RecordSet recordSet = new RecordSet();
        recordSet.writeLog("ruleid="+ruleid+",scopeType="+scopeType+",scopeValue="+scopeValue);
        recordSet.executeQuery(sql);
        while (recordSet.next()) {
            String tmp_id = Util.null2String(recordSet.getString("id"));
            String tmp_ruleid = Util.null2String(recordSet.getString("ruleid"));
            String tmp_scopetype = Util.null2String(recordSet.getString("scopetype"));
            String tmp_scopevalue = Util.null2String(recordSet.getString("scopevalue"));
            String tmp_distributionmode = Util.null2String(recordSet.getString("distributionmode"));
            recordSet.writeLog("tmp_id="+tmp_id+",tmp_ruleid="+tmp_ruleid+",tmp_scopetype="+tmp_scopetype+",tmp_scopevalue="+tmp_scopevalue);
            if(tmp_ruleid.equals(ruleid) && ("".equals(ruleDetailId) || !tmp_id.equals(ruleDetailId))){
                //同一个假期类型，不能同时设置为【加班自动计入调休】和其他的规则，比如按工龄自动发放
                if(!tmp_distributionmode.equals("5")){
                    result.put("flag","1");
                    result.put("msg", SystemEnv.getHtmlLabelName(546798, user.getLanguage()));
                    return result;
                }
            }

            if(tmp_distributionmode.equals("5") && tmp_scopetype.equals(Util.null2String(scopeType)) && ("".equals(ruleDetailId) || !tmp_id.equals(ruleDetailId))){
                //总部级别的范围单独处理下，因为存在之前是分部级别，维护了分部id，这个时候即便是scopytype=0，但是scopevalue依然有值了，所以总部级别不用进行scopevalue的比对
                if("0".equals(tmp_scopetype)){
                    result.put("flag","1");
                    result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage()));
                    return result;
                }
                if(null != scopeValue && scopeValue.indexOf(",")>-1){
                    String[] values = scopeValue.split(",");
                    for (String value : values) {
                        if((","+tmp_scopevalue+",").indexOf(","+value+",")>-1){
                            result.put("flag","1");
                            result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage()));
                            return result;
                        }
                    }
                }else {
                    if((","+tmp_scopevalue+",").indexOf(","+scopeValue+",")>-1){
                        result.put("flag","1");
                        result.put("msg", SystemEnv.getHtmlLabelName(546797, user.getLanguage()));
                        return result;
                    }
                }
            }
        }

        return result;
    }

    /**
     * 是否是育儿假，且不开启叠加
     * @param ruleId
     * @return
     */
    public static boolean isLeaveOfParental(String ruleId){
        boolean flag = false;
        try {
            String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=8 and ruleId=?";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql, ruleId);
            if (recordSet.next()) {
                String severalChildren = Util.null2s(recordSet.getString("severalChildren"), "0");
                if(severalChildren.equals("0")){
                    flag = true;
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return flag;
    }
    /**
     * 是否是育儿假且开启了叠加
     * @param ruleId
     * @return
     */
    public static boolean isLeaveOfParentalNum(String ruleId){
        boolean flag = false;
        try {
            String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=8 and ruleId=?";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql, ruleId);
            if (recordSet.next()) {
                String severalChildren = Util.null2s(recordSet.getString("severalChildren"), "0");
                if(severalChildren.equals("1")){
                    flag = true;
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return flag;
    }

    /**
     * 半天单位 时间选择方式：1-下拉框选择 、2-具体时间
     * @param ruleId
     * @return
     */
    public static int getTimeselection(String ruleId) {
        int timeselection = 1;//最小请假单位
        KQLeaveRulesComInfo kqLeaveRulesComInfo = new KQLeaveRulesComInfo();
        timeselection = Util.getIntValue(kqLeaveRulesComInfo.getTimeSelection(ruleId), 1);
        return timeselection;
    }

    public void updateChildLeaveDate(int scopeType,String scopeValue,int validityRule,String ruleId){
        RecordSet rs = new RecordSet();
        try {
            // 查询当年育儿假数据
            String sql = "select * from kq_balanceOfLeave where  (isDelete is null or isDelete<>1) and leaveRulesId = "+ruleId ;

            if (scopeType == 1 ) {
                sql += " and resourceid in (select id from hrmresource where subCompanyId1 in (" + scopeValue + ") )";
            }else if (scopeType == 2 ) {
                sql += " and resourceid in (select id from hrmresource where departmentId in (" + scopeValue + ") )";
            }else if (scopeType == 3) {
                sql += " and  (" + Tools.getOracleSQLIn(scopeValue, "resourceid")   + ") ";
            }
            KQBalanceOfLeaveEntity balanceEntity = null;
            ArrayList<KQBalanceOfLeaveEntity> balanceEntities = new ArrayList<>();
            rs.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt("id");
                String childId = Util.null2s(rs.getString("childId"), "");
                if(StringUtils.isNotBlank(childId)){
                    String expirationDate = Util.null2s(rs.getString("expirationDate"), "");
                    String effectiveDate = Util.null2s(rs.getString("effectiveDate"), "");
                    balanceEntity = new KQBalanceOfLeaveEntity();
                    balanceEntity.setId(id);
                    balanceEntity.setExpirationDate(expirationDate);
                    balanceEntity.setEffectiveDate(effectiveDate);
                    balanceEntities.add(balanceEntity);
                }
            }
            sql = " update kq_balanceOfLeave set expirationDate =? where id= ? ";
            for (int i = 0; balanceEntities != null && i < balanceEntities.size(); i++) {
                KQBalanceOfLeaveEntity balance = balanceEntities.get(i);
                String uid = Util.null2String(balance.getId());
                String effectiveDate = Util.null2String(balance.getEffectiveDate());
                String expirationDate = "2222-12-31";
                if (validityRule != 0) {
                    expirationDate = TimeUtil.dateAdd(TimeUtil.yearAdd(effectiveDate, 1), -1);
                }
                rs.executeUpdate(sql, expirationDate,uid);
            }

        }catch (Exception e){
            e.printStackTrace();
            rs.writeLog(e);
        }
    }
}
